var userTemplate;
var currentPage = 1;

function setUp(){
	$('#filterOptions').buttonset();

	// Get the fragment for the list item.
	getFragment("userListTemplate", function(data){
		userTemplate = data;
	});

	$('#PBInvokeSearch').bind('click', function(){ performUserFilter(); });
	$('#PBRemoveUsers').bind('click', function(){ removeSelectedUsers(); });
	$('#PBPromoteUsers').bind('click', function(){ promoteSelectedUsers(); });
	$('#PBDemoteUsers').bind('click', function(){ demoteSelectedUsers(); });
	$('#PBActivateUsers').bind('click', function(){ activateSelectedUsers() });
	$('#PBDeactivateUsers').bind('click', function(){ deactivateSelectedUsers() });
}

function activateSelectedUsers(){
	toActivate = $('input[type=checkbox]:checked').parents('label');
	
	if(toActivate.length > 0){
		var confirmed = confirm(PicBoard.languageMap.lang_203_activateUsers);
		var idsToActivate = { ids:[] };
		var objectsToActivate = [];
		
		if(confirmed){
			toActivate.each(function(i){
				data = $(this).data('originalData');
				objectsToActivate.push( $(this) );
				idsToActivate.ids.push(data.uID);
			});
			
			$.post(PicBoard.baseURL + 'rsrc.php?req=activateUsers', $.param(idsToActivate), function(data){
				if(data.statusCode == 200){
					$.each(objectsToActivate, function(i, v){
						$(v).find('.userStatusIcon').attr('src', '../images/status.png');
						$(v).find('input[type=checkbox]').attr('checked', '');
					});
				} else {
					jQuery.facebox(data.message);
				}
			}, 'json' );
			
		}
	}	
}

function deactivateSelectedUsers(){
	toDeactivate = $('input[type=checkbox]:checked').parents('label');
	
	if(toDeactivate.length > 0){
		
		var confirmed = confirm(PicBoard.languageMap.lang_202_deactivateUsers);
		var idsToDeactivate = { ids:[] };
		var objectsToDeactivate = [];
		
		if(confirmed){
			toDeactivate.each(function(i){
				data = $(this).data('originalData');
				objectsToDeactivate.push( $(this) );
				idsToDeactivate.ids.push(data.uID);
			});
			
			$.post(PicBoard.baseURL + 'rsrc.php?req=deactivateUsers', $.param(idsToDeactivate), function(data){
				if(data.statusCode == 200){
					$.each(objectsToDeactivate, function(i, v){
						$(v).find('.userStatusIcon').attr('src', '../images/status-busy.png');
						$(v).find('input[type=checkbox]').attr('checked', '');
					});
				} else {
					jQuery.facebox(data.message);
				}
			}, 'json' );
			
		}
	}	
}

function demoteSelectedUsers(){
	toDemote = $('input[type=checkbox]:checked').parents('label');
	
	if(toDemote.length > 0){
		var confirmed = confirm(PicBoard.languageMap.lang_206_demoteUsers);
		var idsToDemote = { ids:[] };
		var objectsToDemote = [];
		
		if(confirmed){
			toDemote.each(function(i){
				data = $(this).data('originalData');
				objectsToDemote.push( $(this) );
				idsToDemote.ids.push(data.uID);
			});
			
			$.post(PicBoard.baseURL + 'rsrc.php?req=demoteUsers', $.param(idsToDemote), function(data){
				if(data.statusCode == 200){
					$.each(objectsToDemote, function(i, v){
						$(v).find('.userImageIcon').attr('src', '../images/user_blue_32.png');
						$(v).find('input[type=checkbox]').attr('checked', '');
					});
				} else {
					jQuery.facebox(data.message);
				}
			}, 'json' );
			
		}
	}
}

function promoteSelectedUsers(){
	toPromote = $('input[type=checkbox]:checked').parents('label');
	
	if(toPromote.length > 0){
		var confirmed = confirm(PicBoard.languageMap.lang_204_promoteUsers);
		var idsToPromote = { ids:[] };
		var objectsToPromote = [];
		
		if(confirmed){
			toPromote.each(function(i){
				data = $(this).data('originalData');
				objectsToPromote.push( $(this) );
				idsToPromote.ids.push(data.uID);
			});
			
			$.post(PicBoard.baseURL + 'rsrc.php?req=promoteUsers', $.param(idsToPromote), function(data){
				if(data.statusCode == 200){
					$.each(objectsToPromote, function(i, v){
						$(v).find('.userImageIcon').attr('src', '../images/user_business_32.png');
						$(v).find('input[type=checkbox]').attr('checked', '');
					});
				} else {
					jQuery.facebox(data.message);
				}
			}, 'json' );
			
		}
	}
}

function removeSelectedUsers(){
	toRemove = $('input[type=checkbox]:checked').parents('label');
	
	if(toRemove.length > 0){
		var confirmed = confirm(PicBoard.languageMap.lang_205_removeUsers);
		var objectsToRemove = [];
		var idsToRemove = { ids:[] };
		
		if(confirmed){
			toRemove.each(function(i){
				data = $(this).data('originalData');
				objectsToRemove.push( $(this) );
				idsToRemove.ids.push(data.uID);
			});
	
			$.post(PicBoard.baseURL + 'rsrc.php?req=removeUsers', $.param(idsToRemove), function(data){
				if(data.statusCode == 200){
					removeFromList(objectsToRemove);
				} else {
					alert(data.message);
				}
			}, 'json');	
		
		}
	}
}

function removeFromList(objects){
	$.each(objects, function(i, object){
		$(object).animate({ opacity: 0, height: 0, margin:0, padding:0 }, 400, function(){ $(this).remove(); });
	});
}

function performUserFilter(){
	$.post(PicBoard.baseURL + 'rsrc.php?req=getUserList', $('form').serialize(), function(data) {
		if(data.statusCode == 200){
			buildList(data.list, data.number, data.pages);
		} else {
			alert(data.message);
		}
	}, 'json');
}


function buildList(list, results, pages){
	
	$('#infoPane').html("");
	
	if(results > 0){
	
		$.each(list, function(i, v){
			var currentTemplate = userTemplate;
			var originalData = jQuery.extend({}, v);
			
			var information = "Email: " + this.emailAddress + ".";
			if(this.isGlobalAdmin == "1") {
				this.lastName += " (Global Admin)";
				currentTemplate = currentTemplate.replace(/{icon}/ig, "user_business_32");	
			} else {
				currentTemplate = currentTemplate.replace(/{icon}/ig, "user_blue_32");	
			}
			
			if(this.active == "1"){
				currentTemplate = currentTemplate.replace(/{stat}/ig, "status");
				currentTemplate = currentTemplate.replace(/{userStatus}/ig, "User is Active");
			} else {
				currentTemplate = currentTemplate.replace(/{stat}/ig, "status-busy");
				currentTemplate = currentTemplate.replace(/{userStatus}/ig, "User is Inctive");
			}
			
			currentTemplate = currentTemplate.replace(/{firstName}/ig, this.firstName);
			currentTemplate = currentTemplate.replace(/{lastName}/ig, this.lastName);
			currentTemplate = currentTemplate.replace(/{i}/ig, i);			
			currentTemplate = currentTemplate.replace(/{information}/ig, information);
			
			$("#infoPane").append( $(currentTemplate) );
			
			// Store the original data
			$('label[for=check' + i + ']').data('originalData', originalData);
			
		});
		
		$('#ResultsFooter').html($("<div>", { id: 'resultsInfoPane', html:$('<div>', { id:'userNumResults', text: "Number of results: " + results  + " over "  + pages + " pages" }) }));
		
		if(pages > 1){
			previousLink = $('<a>', { 
				html:'Previous Page', 
				href:'#',
				click: function(){
					if(currentPage > 1){
						$('#userPagination').val(--currentPage);
						performUserFilter();
					}
				} 
			});
			nextLink = $('<a>', {
				html:'Next Page', 
				href:'#',
				click: function(){
					if(currentPage < pages){
						$('#userPagination').val(++currentPage);
						performUserFilter();
					}				
				}
			});
			
			$('#resultsInfoPane').append($('<div>', { id:'userPagination'}).append(previousLink, " | ",  nextLink ));
		}
	
	} else {
		PicBoard.getTranslations('lang_118_noresults', function(data){
			$('#infoPane').html("<div id=\"PBAreaExplain_text\">" + data.payload['lang_118_noresults'] + "</div>");
		});
	}
}

function initialise(){
	PicBoard.getTranslations(['lang_202_deactivateUsers', 'lang_203_activateUsers', 'lang_204_promoteUsers', 'lang_205_removeUsers'], function(data){
		setUp();
	})
}

PicBoard.addLoadEvent( "initialise()" );